package com.john.blog.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.john.blog.common.constant.DateStyle;

/**
 * 日期工具
 * 
 * @author JiangGengchao
 * @date 2018年2月9日
 */
public class DateUtils {

    private final static Logger log = LoggerFactory.getLogger(DateUtils.class);

    private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>();

    private static final Object sync = new Object();

    private static SimpleDateFormat getDateFormat(String pattern) throws RuntimeException {
        SimpleDateFormat dateFormat = threadLocal.get();
        if (dateFormat == null) {
            synchronized (sync) {
                if (dateFormat == null) {
                    dateFormat = new SimpleDateFormat(pattern);
                    dateFormat.setLenient(false);
                    threadLocal.set(dateFormat);
                }
            }
        }
        dateFormat.applyPattern(pattern);
        return dateFormat;
    }

    public static String DateToString(Date date, DateStyle dateStyle) {
        String dateString = null;
        if (dateStyle != null && date != null) {
            try {
                dateString = getDateFormat(dateStyle.getValue()).format(date);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return dateString;
    }

}